<?php

namespace co2_OS;

use co2\dev\v0_0_0 as api;

function run($app,$version=null,$channel='stable')

{
  log::register("RUN: Received run signal for app $app in channel $channel");
  
	$app=strtolower($app);
	
	$aptitude=aptitude::get(aptitude::TYPE_APP,$app,$version,$channel);
	
	if(!count($aptitude))
	
	{
	  $message="The application \"$app\"";
	  
	  if(!is_null($version))
	  $message.=" version \"$version\"";
	  
	  $message.=' is not installed. Type `co2 install app '.$app;
	  
	  if(!is_null($version))
	  $messsage.=' { --version '.$version.' }';
	  
	  $message.='` to install it.';
	  
	  log::register('RUN: App not installed');
	  
	  throw new api\Exception($message,null,EXIT_STATUS::APP_NOT_MANIFESTED);
	}

	if(is_null($version))
	$version=current($aptitude)->version;
	
	log::register('RUN: Running app version '.$version);  

	$Version='v'.preg_replace('/\./','_',$version);
	
	$base=sysvar::get('apps');
	
	$file=$base."/$app/$channel/".'/'.$version.'/run.php'; 
	$class='co2_OS\apps\\'.$app.'\\'.$channel.'\\'.$Version.'\run';

	if(!file_exists($file))
	throw new api\Exception('Cannot run app '.$app.' version '.$version.': run file not found '.$file,null,EXIT_STATUS::FILE_NOT_FOUND);
	
	return new $class;
}
